// Copyright (c) 2011 Blue Onion Software, All rights reserved
using System;
using System.Collections.Specialized;
using System.IO;
using System.Web;
using System.Web.Hosting;
using System.Web.UI.WebControls.WebParts;
using BlueOnionSoftware.Bloget.Providers.Data;

namespace BlueOnionSoftware.Bloget.Providers
{
    public class XmlPersonalizationProvider : PersonalizationProvider
    {
        private string dataStorePath;
        private string applicationName;

        public string DataStorePath
        {
            get { return dataStorePath; }
            set { dataStorePath = value; }
        }

        private string DataStoreFile
        {
            get
            {
                string path;

                if (HttpContext.Current != null)
                {
                    path = HttpContext.Current.Server.MapPath(DataStorePath);
                }

                else
                {
                    path = HostingEnvironment.ApplicationPhysicalPath;
                    var dataStorePath = DataStorePath.Replace("~/", string.Empty);
                    path = Path.Combine(path, dataStorePath);
                }

                return Path.Combine(path, string.Format("{0}_Personalization.xml", applicationName));
            }
        }

        public override string ApplicationName
        {
            get { return applicationName; }
            set { applicationName = value; }
        }

        public override void Initialize(string name, NameValueCollection config)
        {
            Throw.IfNull(config, "config");

            if (String.IsNullOrEmpty(name))
            {
                name = "XmlPersonalizationProvider";
            }

            base.Initialize(name, config);

            dataStorePath = String.IsNullOrEmpty(config["dataStorePath"]) ? "~/App_Data" : config["dataStorePath"];
            applicationName = String.IsNullOrEmpty(config["applicationName"]) ? "Bloget" : config["applicationName"];
        }

        public override PersonalizationStateInfoCollection FindState(PersonalizationScope scope, PersonalizationStateQuery query, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetCountOfState(PersonalizationScope scope, PersonalizationStateQuery query)
        {
            throw new NotImplementedException();
        }

        protected override void LoadPersonalizationBlobs(WebPartManager webPartManager, string path, string userName, ref byte[] sharedDataBlob, ref byte[] userDataBlob)
        {
            var spaces = WorkspaceCollection.Load(DataStoreFile);

            if (spaces.SharedPersonalizationBlob != null)
            {
                sharedDataBlob = spaces.SharedPersonalizationBlob;
            }

            var space = spaces.FindByUserAndPath(userName, path);

            if (space != null && space.PersonalizationBlob != null)
            {
                userDataBlob = space.PersonalizationBlob;
            }
        }

        protected override void ResetPersonalizationBlob(WebPartManager webPartManager, string path, string userName)
        {
            var spaces = WorkspaceCollection.Load(DataStoreFile);
            var space = spaces.FindByUserAndPath(userName, path);

            if (space != null)
            {
                spaces.Workspaces.Remove(space);
                spaces.Save(DataStoreFile);
            }
        }

        /// <returns>The number of rows deleted.</returns>
        public override int ResetState(PersonalizationScope scope, string[] paths, string[] usernames)
        {
            throw new NotImplementedException();
        }

        public override int ResetUserState(string path, DateTime userInactiveSinceDate)
        {
            throw new NotImplementedException();
        }

        protected override void SavePersonalizationBlob(WebPartManager webPartManager, string path, string userName, byte[] dataBlob)
        {
            var spaces = WorkspaceCollection.Load(DataStoreFile);

            if (!String.IsNullOrEmpty(userName))
            {
                var space = spaces.FindByUserAndPath(userName, path);

                if (space == null)
                {
                    space = new Workspace();
                    space.Path = path;
                    space.UserName = userName;
                    spaces.Workspaces.Add(space);
                }

                space.PersonalizationBlob = dataBlob;
            }

            else
            {
                spaces.SharedPersonalizationBlob = dataBlob;
            }

            spaces.Save(DataStoreFile);
        }
    }
}